<template>
  <div class="create-order">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>创建回收订单</h2>
      <p>选择回收物品并填写取货信息</p>
    </div>

    <el-form 
      ref="orderFormRef"
      :model="orderForm" 
      :rules="orderRules" 
      label-width="120px"
      class="order-form"
    >
      <!-- 回收物品选择 -->
      <el-card shadow="never" class="form-section">
        <template #header>
          <div class="card-header">
            <span>选择回收物品</span>
            <div class="draft-info" v-if="selectedItems.length > 0">
              <el-tag type="success" size="small">
                <el-icon><Document /></el-icon>
                物品已自动保存
              </el-tag>
              <el-button 
                type="danger" 
                size="small" 
                text
                @click="confirmClearDraft"
              >
                清空物品
              </el-button>
            </div>
          </div>
        </template>
        <div class="items-grid">
          <div 
            v-for="item in availableItems" 
            :key="item.id"
            class="item-card"
            :class="{ 'selected': isItemSelected(item.id) }"
            @click="toggleItem(item)"
          >
            <div class="item-header">
              <h4>{{ item.name }}</h4>
              <el-tag size="small">{{ item.category }}</el-tag>
            </div>
            <div class="item-price">
              <span class="price">¥{{ item.price }}</span>
              <span class="unit">/{{ item.unit }}</span>
            </div>
            <div class="item-description">
              {{ item.description }}
            </div>
            <div class="item-actions" v-if="isItemSelected(item.id)" @click.stop>
              <el-input-number
                v-model="getSelectedItem(item.id).quantity"
                :min="0.1"
                :step="item.unit === 'kg' ? 0.1 : 1"
                :precision="item.unit === 'kg' ? 1 : 0"
                size="small"
                @change="updateItemTotal"
              />
              <span class="unit-label">{{ item.unit }}</span>
            </div>
          </div>
        </div>
        
        <!-- 选中物品汇总 -->
        <div v-if="selectedItems.length > 0" class="selected-summary">
          <h4>已选择的物品</h4>
          <el-table :data="selectedItems" style="width: 100%" size="small">
            <el-table-column prop="name" label="物品名称" width="120" />
            <el-table-column prop="category" label="分类" width="80" />
            <el-table-column prop="quantity" label="重量/数量" width="80">
              <template #default="scope">
                {{ scope.row.quantity }}{{ scope.row.unit }}
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" width="80">
              <template #default="scope">
                ¥{{ scope.row.price }}/{{ scope.row.unit }}
              </template>
            </el-table-column>
            <el-table-column prop="subtotal" label="小计" width="80">
              <template #default="scope">
                ¥{{ (scope.row.quantity * scope.row.price).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeItem(scope.row.id)"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="total-amount">
            <strong>总金额: ¥{{ totalAmount.toFixed(2) }}</strong>
          </div>
        </div>
      </el-card>

      <!-- 取货信息 -->
      <el-card title="取货信息" shadow="never" class="form-section">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="取货地址" prop="pickupAddress">
              <el-input 
                v-model="orderForm.pickupAddress" 
                type="textarea" 
                placeholder="请输入详细的取货地址（联系人信息将自动使用您的账户信息）"
                :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="预约时间" prop="pickupTime">
              <el-date-picker
                v-model="orderForm.pickupTime"
                type="datetime"
                placeholder="选择取货时间"
                :disabled-date="disabledDate"
                :disabled-hours="disabledHours"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="偏好站点" prop="preferredStation">
              <el-select 
                v-model="orderForm.preferredStation" 
                placeholder="选择偏好的回收站点"
                style="width: 100%"
              >
                <el-option 
                  v-for="station in availableStations"
                  :key="station.id"
                  :label="station.name"
                  :value="station.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注信息">
          <el-input 
            v-model="orderForm.notes" 
            type="textarea" 
            placeholder="如有特殊要求或备注信息，请在此说明"
            :rows="3"
          />
        </el-form-item>
      </el-card>

      <!-- 订单确认 -->
      <el-card title="订单确认" shadow="never" class="form-section">
        <div class="order-summary">
          <div class="summary-row">
            <span>物品总重量:</span>
            <span>{{ totalWeight.toFixed(1) }}kg</span>
          </div>
          <div class="summary-row">
            <span>预计收益:</span>
            <span class="amount">¥{{ totalAmount.toFixed(2) }}</span>
          </div>
          <div class="summary-row">
            <span>取货地址:</span>
            <span>{{ orderForm.pickupAddress || '未填写' }}</span>
          </div>
          <div class="summary-row">
            <span>预约时间:</span>
            <span>{{ formatDateTime(orderForm.pickupTime) || '未选择' }}</span>
          </div>
        </div>

        <div class="form-actions">
          <el-button size="large" @click="resetForm">重置</el-button>
          <el-button 
            type="primary" 
            size="large" 
            @click="submitOrder"
            :loading="submitting"
            :disabled="!canSubmit"
          >
            {{ submitting ? '提交中...' : '提交订单' }}
          </el-button>
        </div>
      </el-card>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import { itemsAPI, ordersAPI, stationsAPI } from '@/api'

// 组件名称
defineOptions({
  name: 'CreateRecycleOrder'
})

const router = useRouter()
const store = useStore()
const orderFormRef = ref()
const submitting = ref(false)
const loading = ref(false)

// 所有物品（从API加载）
const allItems = ref([])

// 可用物品（只显示可回收的）
const availableItems = computed(() => {
  return allItems.value.filter(item => item.status === 'active')
})

// 加载物品列表
const loadItems = async () => {
  try {
    loading.value = true
    const response = await itemsAPI.getItems({
      page: 1,
      pageSize: 1000,
      status: '' // 获取所有状态的物品
    })
    
    const itemList = response.list || response.data || response || []
    
    // 转换数据格式以匹配页面需求
    allItems.value = itemList.map(item => ({
      id: item.id,
      name: item.name,
      category: item.category,
      unit: item.unit,
      price: item.pricePerUnit || item.price,
      description: item.description,
      status: item.status,
      image: item.image
    }))
  } catch (error) {
    console.error('加载物品列表失败:', error)
    ElMessage.error('连接服务器失败，请稍后重试')
    allItems.value = []
  } finally {
    loading.value = false
  }
}

// 可用站点（从 API 动态加载）
const availableStations = ref([])

// 加载可用站点
const loadStations = async () => {
  try {
    const response = await stationsAPI.getAvailableStations()
    const stationList = response.data || response || []
    availableStations.value = stationList.filter(s => s.status === 'active')
  } catch (error) {
    console.error('加载站点列表失败:', error)
    availableStations.value = []
  }
}

// 选中的物品（带本地存储）
const selectedItems = ref([])

// 保存已选物品到本地存储
const saveSelectedItemsToLocal = () => {
  try {
    localStorage.setItem('draft_order_items', JSON.stringify(selectedItems.value))
  } catch (error) {
    console.error('保存订单失败:', error)
  }
}

// 从本地存储加载已选物品
const loadSelectedItemsFromLocal = () => {
  try {
    const savedItems = localStorage.getItem('draft_order_items')
    if (savedItems) {
      const items = JSON.parse(savedItems)
      // 验证数据有效性
      if (Array.isArray(items) && items.length > 0) {
        selectedItems.value = items
        ElMessage.info(`已恢复 ${items.length} 个物品`)
        return true
      }
    }
  } catch (error) {
    console.error('加载订单失败:', error)
  }
  return false
}

// 清除本地存储的订单物品
const clearOrderDraft = () => {
  try {
    localStorage.removeItem('draft_order_items')
  } catch (error) {
    console.error('清除订单失败:', error)
  }
}

// 订单表单
const orderForm = reactive({
  pickupAddress: '',
  pickupTime: null,
  preferredStation: null,
  notes: ''
})

// 表单验证规则
const orderRules = {
  pickupAddress: [
    { required: true, message: '请输入取货地址', trigger: 'blur' }
  ],
  pickupTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ]
}

// 计算属性
const totalAmount = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + (item.quantity * item.price)
  }, 0)
})

const totalWeight = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    if (item.unit === 'kg') {
      return total + item.quantity
    }
    return total
  }, 0)
})

const canSubmit = computed(() => {
  return selectedItems.value.length > 0 && 
         orderForm.pickupAddress && 
         orderForm.pickupTime
})

// 方法
const isItemSelected = (itemId) => {
  return selectedItems.value.some(item => item.id === itemId)
}

const getSelectedItem = (itemId) => {
  return selectedItems.value.find(item => item.id === itemId)
}

const toggleItem = (item) => {
  const index = selectedItems.value.findIndex(selected => selected.id === item.id)
  
  if (index > -1) {
    selectedItems.value.splice(index, 1)
  } else {
    selectedItems.value.push({
      ...item,
      quantity: item.unit === 'kg' ? 1.0 : 1
    })
  }
  
  // 自动保存到本地存储
  saveSelectedItemsToLocal()
}

const removeItem = (itemId) => {
  const index = selectedItems.value.findIndex(item => item.id === itemId)
  if (index > -1) {
    selectedItems.value.splice(index, 1)
    // 自动保存到本地存储
    saveSelectedItemsToLocal()
  }
}

const updateItemTotal = () => {
  // 触发重新计算并保存
  saveSelectedItemsToLocal()
}

const disabledDate = (time) => {
  // 不能选择今天之前的日期
  return time.getTime() < Date.now() - 8.64e7
}

const disabledHours = () => {
  // 营业时间 8:00-18:00
  const hours = []
  for (let i = 0; i < 8; i++) {
    hours.push(i)
  }
  for (let i = 18; i < 24; i++) {
    hours.push(i)
  }
  return hours
}

const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return datetime.toLocaleString('zh-CN')
}

const resetForm = () => {
  selectedItems.value = []
  Object.assign(orderForm, {
    pickupAddress: '',
    pickupTime: null,
    preferredStation: null,
    notes: ''
  })
  if (orderFormRef.value) {
    orderFormRef.value.resetFields()
  }
  // 清除本地存储的物品
  clearOrderDraft()
}

const confirmClearDraft = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有已选择的物品吗？此操作不可恢复。',
      '清空物品',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    selectedItems.value = []
    clearOrderDraft()
    ElMessage.success('已清空物品')
  } catch {
    // 用户取消
  }
}

const submitOrder = async () => {
  if (!orderFormRef.value) return
  
  try {
    await orderFormRef.value.validate()
    
    if (selectedItems.value.length === 0) {
      ElMessage.warning('请至少选择一种回收物品')
      return
    }
    
    submitting.value = true
    
    // 构建订单数据
    const orderData = {
      // 订单物品列表
      items: selectedItems.value.map(item => ({
        itemId: item.id,
        quantity: item.quantity
      })),
      // 取货信息
      pickupAddress: orderForm.pickupAddress,
      pickupTime: orderForm.pickupTime ? orderForm.pickupTime.toISOString() : null,
      // 偏好站点（可选）
      stationId: orderForm.preferredStation || null,
      // 备注
      notes: orderForm.notes || ''
    }
    
    // 调用真实API创建订单
    const response = await ordersAPI.createOrder(orderData)
    
    ElMessage.success('订单提交成功！')
    
    // 清空购物车
    store.commit('CLEAR_CART')
    
    // 清除本地存储的订单物品
    clearOrderDraft()
    
    // 显示订单确认信息
    const orderNo = response.orderNo || response.data?.orderNo || `RC${Date.now()}`
    await ElMessageBox.alert(
      `订单已提交成功！\n订单号: ${orderNo}\n预计收益: ¥${totalAmount.value.toFixed(2)}\n我们会尽快安排回收员上门取货。`,
      '订单提交成功',
      {
        confirmButtonText: '查看订单',
        type: 'success'
      }
    )
    
    // 跳转到订单列表
    router.push('/customer/orders')
    
  } catch (error) {
    console.error('订单提交失败:', error)
    
    if (error !== 'cancel') {
      // 获取后端返回的错误信息
      const errorMsg = error.response?.data?.message 
        || error.message 
        || '订单提交失败，请重试'
      ElMessage.error(errorMsg)
    }
  } finally {
    submitting.value = false
  }
}

// 初始化购物车物品
const initCartItems = () => {
  const cartItems = store.getters.cartItems
  if (cartItems && cartItems.length > 0) {
    let addedCount = 0
    let skippedCount = 0
    
    // 将购物车中的物品添加到已选择列表（仅添加可回收的）
    cartItems.forEach(item => {
      // 检查物品状态，只添加可回收的物品
      if (item.status === 'active' && !selectedItems.value.find(selected => selected.id === item.id)) {
        selectedItems.value.push({
          ...item,
          quantity: item.quantity || (item.unit === 'kg' ? 1.0 : 1)
        })
        addedCount++
      } else if (item.status === 'inactive') {
        skippedCount++
      }
    })
    
    // 提示用户
    if (addedCount > 0) {
      ElMessage.success(`已为您添加 ${addedCount} 个物品`)
    }
    
    if (skippedCount > 0) {
      ElMessage.warning(`${skippedCount} 个物品已暂停回收，已自动移除`)
      // 从购物车中移除暂停回收的物品
      cartItems.forEach(item => {
        if (item.status === 'inactive') {
          store.commit('REMOVE_FROM_CART', item.id)
        }
      })
    }
  }
}

// 页面加载时初始化
onMounted(async () => {
  // 加载物品列表和站点列表
  await Promise.all([
    loadItems(),
    loadStations()
  ])
  
  // 尝试恢复本地物品
  const hasDraft = loadSelectedItemsFromLocal()
  
  // 如果没有物品，再从购物车加载
  if (!hasDraft) {
    initCartItems()
  } else {
    // 如果有物品，仍然检查购物车中是否有新物品需要添加
    const cartItems = store.getters.cartItems
    if (cartItems && cartItems.length > 0) {
      let newItemsCount = 0
      cartItems.forEach(item => {
        if (item.status === 'active' && !selectedItems.value.find(selected => selected.id === item.id)) {
          selectedItems.value.push({
            ...item,
            quantity: item.quantity || (item.unit === 'kg' ? 1.0 : 1)
          })
          newItemsCount++
        }
      })
      
      if (newItemsCount > 0) {
        ElMessage.success(`已添加 ${newItemsCount} 个新物品`)
        saveSelectedItemsToLocal()
      }
    }
  }
})
</script>

<style scoped>
.create-order {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.form-section {
  margin-bottom: 24px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
}

.draft-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.items-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.item-card {
  padding: 16px;
  border: 2px solid #e6e6e6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.item-card:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.item-card.selected {
  border-color: #409EFF;
  background-color: #f0f8ff;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.item-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.item-price {
  margin-bottom: 8px;
}

.price {
  font-size: 18px;
  font-weight: bold;
  color: #67C23A;
}

.unit {
  font-size: 14px;
  color: #999;
}

.item-description {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 12px;
}

.item-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.unit-label {
  font-size: 12px;
  color: #999;
}

.selected-summary {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.selected-summary h4 {
  margin: 0 0 16px 0;
  color: #333;
}

.total-amount {
  text-align: right;
  margin-top: 16px;
  font-size: 16px;
  color: #333;
}

.order-summary {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 24px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
}

.summary-row:last-child {
  margin-bottom: 0;
}

.summary-row .amount {
  font-size: 18px;
  font-weight: bold;
  color: #67C23A;
}

.form-actions {
  text-align: center;
  gap: 16px;
  display: flex;
  justify-content: center;
}

.form-actions .el-button {
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .items-grid {
    grid-template-columns: 1fr;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
}
</style>
